package com.ganbo.stock.service.impl;

import com.ganbo.stock.entity.Fund;
import com.ganbo.stock.entity.FundStock;
import com.ganbo.stock.utils.RestTemplateUtils;
import com.ganbo.stock.utils.ThreadUtils;
import com.ganbo.stock.dto.FundStockDTO;
import com.ganbo.stock.dto.FundStockDataDTO;
import com.ganbo.stock.dto.FundStockFetchDataDTO;
import com.ganbo.stock.repository.FundRepository;
import com.ganbo.stock.repository.FundStockRepository;
import com.ganbo.stock.service.FundStockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 基金持仓股票
 *
 * @Author: ganbo
 * @Date: 2021/2/6 17:06
 */

@Service
@Slf4j
public class FundStockServiceImpl extends BaseService implements FundStockService {

    @Autowired
    FundRepository fundRepository;
    @Autowired
    RestTemplateUtils restTemplateUtils;
    @Autowired
    FundStockRepository fundStockRepository;
    @Autowired
    FundStockLastServiceImpl fundStockLastServiceImpl;

    //https://danjuanfunds.com/djapi/fund/asset_conf?fd_code=004040
    private final String url = "https://danjuanfunds.com/djapi/fund/asset_conf?fd_code";

    @Transactional
    public void fetchFundStockTask() {

        log.info("===========================>开始拉取基金持仓的股票信息<=======================");
        List<Fund> funds = fundRepository.findAll();
        Map<String, String> params = new HashMap<>();
        if (CollectionUtils.isEmpty(funds)) return;

        long startTime = System.currentTimeMillis();
        for (int i = 0; i < funds.size(); i++) {
            ThreadUtils.sleepSeconds(1);
            Fund fund = funds.get(i);
            String code = fund.getCode();

            String url = getUrl(code);
            FundStockFetchDataDTO fundStockDataDTO = restTemplateUtils.get(url, params, FundStockFetchDataDTO.class);
            FundStockDataDTO fundStockData = fundStockDataDTO.getData();
            if (fundStockData == null) continue;
            List<FundStockDTO> stockList = fundStockData.getStock_list();
            if (CollectionUtils.isEmpty(stockList)) continue;

            log.info("{}/{}==成功获取基金（{}）的持仓股票", (i + 1), funds.size(), fund.getName());
            List<FundStock> fundStocks = new ArrayList<>();
            for (FundStockDTO fundStockDTO : stockList) {

                //排除A股主板、创业板、st以外的股票
                String stockCode = fundStockDTO.getCode();
                if (!stockCode.startsWith("300") && !stockCode.startsWith("60") && !stockCode.startsWith("00"))
                    continue;
                if (stockCode.length() != 6 || fundStockDTO.getName().startsWith("ST")) continue;

                FundStock fundStock = new FundStock();
                fundStock.setFundName(fund.getName());
                fundStock.setFundCode(fund.getCode());
                fundStock.setName(fundStockDTO.getName());
                fundStock.setCode(fundStockDTO.getCode());
                fundStock.setCurrentPrice(fundStockDTO.getCurrent_price());
                fundStock.setChangePercentage(fundStockDTO.getChange_percentage());
                fundStock.setPercent(fundStockDTO.getPercent());
                fundStock.setXqUrl(fundStockDTO.getXq_url());
                fundStock.setXqSymbol(fundStockDTO.getXq_symbol());
                fundStocks.add(fundStock);
                fundStock.setCycle(fund.getCycle());
            }
            fundStockRepository.saveAll(fundStocks);
        }
        log.info("===========================>拉取基金持仓的股票信息完毕，耗时:{}秒<=======================", (System.currentTimeMillis() - startTime) / 1000);
    }

    private String getUrl(String fundCode) {
        return url.replace("fd_code", "fd_code=" + fundCode);
    }


}
